package com.hphs.advice;

import cn.hutool.json.JSONUtil;
import com.hphs.dto.ResponseDTO;
import com.hphs.info.PageInfo;
import com.hphs.threadlocal.LocalPageInfoUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;
import java.util.Map;

// 针对controller做的增强类
@RestControllerAdvice
public class MyResponseAdvice implements ResponseBodyAdvice<Object> {
    //默认不对任何接口增强
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        //打开增强器
        return true;
    }
    // 错信息的统一管理
    @ExceptionHandler
    public Object processException(Exception ex){
        //设定执行逻辑
        ResponseDTO dto =ResponseDTO.error(1,ex.getMessage());
        return dto;
    }


    @Override
    public Object beforeBodyWrite(
            Object body,
            MethodParameter methodParameter,
            MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass,
            ServerHttpRequest serverHttpRequest,
            ServerHttpResponse serverHttpResponse) {
        // 解决双重包裹的问题
        if(body instanceof ResponseDTO){
            return body;
        }
        // 引入DTO对象 统一返回值管理
        ResponseDTO dto =ResponseDTO.success(body);
        PageInfo pageInfo = LocalPageInfoUtil.get();
        // 如果线程上有分页的信息那么直接获取
        if (pageInfo != null){
            Map<Object,Object> map= new HashMap<>();
            map.put("total",pageInfo.getTotal());
            map.put("items",body);
            // 把map中的数据存入到dto中
            dto=ResponseDTO.success(map);
            // 清空线程共享数据
            LocalPageInfoUtil.remove();
        }


        //返回的是纯字符串的话 就需要把数据转成 json数据
        if (aClass == StringHttpMessageConverter.class){
            return JSONUtil.toJsonStr(dto);
        }

        return dto;
    }
}
